package com.ztstech.ali_vod_video;

import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.aliyun.vod.common.utils.StringUtils;
import com.ztstech.ali_vod_video.alivideo.base.BaseCallBack;
import com.ztstech.ali_vod_video.alivideo.domain.AliVideoModelImpl;
import com.ztstech.ali_vod_video.alivideo.utils.LogUtil;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry.Registrar;

/**
 * AliVodVideoPlugin
 */
public class AliVodVideoPlugin implements FlutterPlugin, MethodCallHandler {

    private MethodChannel channel;
    private Map<String, AliVideoModelImpl> modelMap;
    private Context context;
    private String filePath;
    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        channel = new MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), "ali_vod_video");
        channel.setMethodCallHandler(this);
        context = flutterPluginBinding.getApplicationContext();
        modelMap = new HashMap<>();
    }

    // This static function is optional and equivalent to onAttachedToEngine. It supports the old
    // pre-Flutter-1.12 Android projects. You are encouraged to continue supporting
    // plugin registration via this function while apps migrate to use the new Android APIs
    // post-flutter-1.12 via https://flutter.dev/go/android-project-migration.
    //
    // It is encouraged to share logic between onAttachedToEngine and registerWith to keep
    // them functionally equivalent. Only one of onAttachedToEngine or registerWith will be called
    // depending on the user's project. onAttachedToEngine or registerWith must both be defined
    // in the same class.
    public static void registerWith(Registrar registrar) {
        final MethodChannel channel = new MethodChannel(registrar.messenger(), "ali_vod_video");
        channel.setMethodCallHandler(new AliVodVideoPlugin());
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull final Result result) {
        if (call.method.equals("getPlatformVersion")) {
            result.success("Android " + android.os.Build.VERSION.RELEASE);
        } else if (call.method.equals("uploadVideo")) {
            ///上传视频
            String filePath = call.argument("filePath");
            String id = call.argument("id");
            AliVideoModelImpl aliVideoModel;
            if(modelMap.get(id) == null){
                aliVideoModel = new AliVideoModelImpl();
                modelMap.put(id, aliVideoModel);
            }else {
                aliVideoModel = modelMap.get(id);
            }
            this.filePath = filePath;
            String cateId = call.argument("cateId");
            String templateGroupId = call.argument("templateGroupId");
            String definition = call.argument("definition");
            String userData = call.argument("UserData");
            final boolean needProgress = call.argument("needProgress");
            if(cateId == null || cateId.isEmpty()){
                cateId = "2165";
            }
            final Map<String,Object> map = new HashMap<>();
            map.put("filePath", filePath);
            map.put("id", id);
            aliVideoModel.upLoadVideo(context, cateId, templateGroupId, definition, filePath, userData, needProgress,
                    new BaseCallBack<Map<String,String>>() {
                        @Override
                        public void onSuccess(final Map<String,String> map) {
                            LogUtil.e("视频上传成功："+map.toString());
                            new Handler(context.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    result.success(map);
                                }
                            });
                        }

                        @Override
                        public void onFail(final String msg) {
                            new Handler(context.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(context, ""+msg,Toast.LENGTH_LONG).show();
                                    result.error("-1",msg,msg);
                                }
                            });
                        }

                        @Override
                        public void onProgress(final float percent) {
                            map.put("progress", percent);
                            new Handler(context.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    if(!needProgress){
                                        LogUtil.e("视频正在上传："+percent);
                                    }
                                    channel.invokeMethod("onUploadProgressChange", map);
                                }
                            });
                        }
                    });
        }else if (call.method.equals("cancelUploadVideo")) {
            ///取消上传视频
            String filePath = call.argument("filePath");
            String id = call.argument("id");
            AliVideoModelImpl aliVideoModel = modelMap.get(id);
            if(aliVideoModel != null){
                aliVideoModel.cancelUpLoadVideo();
                final Map<String,Object> tempMap = new HashMap<>();
                tempMap.put("filePath", filePath);
                tempMap.put("id", id);
                channel.invokeMethod("onUploadCancel", tempMap);
                LogUtil.e("视频取消上传："+filePath);
            }

        }else if(call.method.equals("cancelUploadVideoAll")){
            Iterator<AliVideoModelImpl> iterator = modelMap.values().iterator();
            while (iterator.hasNext()){
                AliVideoModelImpl aliVideoModel = iterator.next();
                if(aliVideoModel != null){
                    aliVideoModel.cancelUpLoadVideo();
                    LogUtil.e("视频全部取消上传");
                }
            }

        } else if (call.method.equals("uploadVideoWithCompass")) {
            ///先压缩再上传视频
        } else {
            result.notImplemented();
        }
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        channel.setMethodCallHandler(null);
    }
}
